﻿
using System;
using System.Diagnostics;
using System.Threading;
using System.Collections.Generic;
namespace Codemonk.Common.Diagnostic
{
    /// <summary>
    /// 行为计时器
    /// </summary>
    public static class ActionTimer
    {
        private static void EmptyAction() { }

        static ActionTimer()
        {
            Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.High;
            Thread.CurrentThread.Priority = ThreadPriority.Highest;
            Time(EmptyAction, 1);
        }

        public static TimerResult Time(Action action, int iteration = 1)
        {
            GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
            int[] gcCounts = new int[GC.MaxGeneration + 1];
            for (int i = 0; i <= GC.MaxGeneration; i++)
                gcCounts[i] = GC.CollectionCount(i);

            Stopwatch watch = new Stopwatch();
            watch.Start();
            for (int i = 0; i < iteration; i++) action();
            watch.Stop();


            List<Tuple<string, int>> gens = new List<Tuple<string, int>>();
            for (int i = 0; i <= GC.MaxGeneration; i++)
            {
                int count = GC.CollectionCount(i) - gcCounts[i];
                gens.Add(new Tuple<string, int>(string.Concat("Gen", i), count));
            }
            return new TimerResult(watch.ElapsedMilliseconds, gens);
        }
    }
}
